package com.lanou.lenanapp.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.lanou.lenanapp.R;
import com.lanou.lenanapp.adapter.ContributionAdapter;
import com.lanou.lenanapp.beans.Contribution;
import com.lanou.lenanapp.util.Utils;
import com.lanou.lenanapp.view.SwipeRefreshLoadingLayout;
import com.lanou.lenanapp.volley.VolleySingleton;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 网友投稿区
 */
public class ContributionActivity extends Activity implements View.OnClickListener, SwipeRefreshLoadingLayout.OnRefreshListener, SwipeRefreshLoadingLayout.OnLoadListener {

    private RecyclerView contributionRecyclerView;
    private ImageView back_contribution;
    private ContributionAdapter contributionAdapter;
    private GridLayoutManager manager;
    private SwipeRefreshLoadingLayout contributionswipeRefreshLoadingLayout;
    private Dialog dialog;

    VolleySingleton volleySingleton = VolleySingleton.getInstance();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_contribution);

        init();


    }

    private void init() {
        contributionRecyclerView = (RecyclerView) findViewById(R.id.contributionRecyclerView);
        manager = new GridLayoutManager(this, 1);
        contributionAdapter = new ContributionAdapter(this);
        contributionRecyclerView.setLayoutManager(manager);
        contributionRecyclerView.setAdapter(contributionAdapter);

        back_contribution = (ImageView) findViewById(R.id.back_contribution);
        back_contribution.setOnClickListener(this);

        contributionswipeRefreshLoadingLayout = (SwipeRefreshLoadingLayout) findViewById(R.id.contributionswipeRefreshLoadingLayout);
        contributionswipeRefreshLoadingLayout.setOnRefreshListener(this);
        contributionswipeRefreshLoadingLayout.setOnLoadListener(this);

        //判断是否有网络
        boolean geanwen = checkNet(this);
        if (geanwen){
            initData();
        }else {
            Toast.makeText(this, "请检查您的网络..", Toast.LENGTH_SHORT).show();
        }
    }

    /***
     * 判断是否有网络  返回的是boolean类型的
     * **/
    public static boolean checkNet(Context context) {
        try {
            ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                NetworkInfo info = connectivity.getActiveNetworkInfo();
                Log.i("TAG", "info =" + info);
                if (info != null && info.isConnected()) {
                    if (info.getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            Log.e("TAG", "exception=" + e.toString());
            return false;
        }
        return false;
    }


    /** 下拉刷新 **/
    @Override
    public void onRefresh() {
        initData();
    }

    private String time;
    private int t;
    private void initData() {
        dialog = Utils.createloadingDialog(this, "玩命加载中...");
        dialog.show();
        String url = "http://120.55.151.67/weibofun/users/post_list.php?apiver=10700&category=weibo_jokes&page=0&page_size=30&max_timestamp=-1&latest_viewed_ts=1444745160&uid=-1&platform=iphone&appver=1.9&buildver=1.9.4&udid=0FD678F7-07AA-4EBF-BB39-EB79EAB40753&sysver=7.0.4";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                dialog.dismiss();
                contributionswipeRefreshLoadingLayout.setRefreshing(false);
                if(response != null && response.has("items")){
                    try {
                        JSONArray con = response.getJSONArray("items");
                        List<Contribution> contributions = new ArrayList<Contribution>();
                        Gson gson = new Gson();
                        for (int i = 0; i < con.length(); i ++){
                            String str = con.getString(i);
                            Contribution c = gson.fromJson(str, Contribution.class);
                            contributions.add(c);
                        }
                        contributionAdapter.addData(contributions);
                        time = contributions.get(15).getUpdate_time();
                        t = Integer.parseInt(time);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

        volleySingleton.addRequest(request);


    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back_contribution:
                Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                this.finish();
                break;
        }
    }



    /** 上拉加载 **/
    @Override
    public void onLoad() {
        LoadContent();
    }

    int page = 0;
    int tamptimes = 0;
    private void LoadContent() {
        page++;
        tamptimes = tamptimes + 500000;
        t = t - tamptimes;

        String url = "http://120.55.151.67/weibofun/users/post_list.php?apiver=10700&category=weibo_jokes&page="+ page +"&page_size=15&max_timestamp="+
                t +"&latest_viewed_ts=-1&uid=-1&platform=iphone&appver=1.9&buildver=1.9.4&udid=0FD678F7-07AA-4EBF-BB39-EB79EAB40753&sysver=7.0.4";

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                contributionswipeRefreshLoadingLayout.setLoading(false);
                if(response != null && response.has("items")){
                    try {
                        JSONArray con = response.getJSONArray("items");
                        List<Contribution> contributions = new ArrayList<Contribution>();
                        Gson gson = new Gson();
                        for (int i = 0; i < con.length(); i ++){
                            String str = con.getString(i);
                            Contribution c = gson.fromJson(str, Contribution.class);
                            contributions.add(c);
                        }
                        contributionAdapter.loadData(contributions);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

        volleySingleton.addRequest(request);

    }


}
